package com.gz.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet(urlPatterns = "/createCookie")
public class CreateCookie extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("CreateCookie被调用");

        //1.创建一个Cookie对象
        //2.username  改cookie的名字，可以理解为key
        //3.gz :该cookie的值，可以理解为value
        //4.可以创建多个，这里我只创建了一个
        //5.如果这里存放了中文的cookie，会报错，出现乱码
        //6.解决方法:将中文 编程为URL英文编码 英文: encode=编码
        Cookie cookie = new Cookie("username","gz");
        Cookie cookie2 = new Cookie("job","java");
        String basketball = URLEncoder.encode("篮球", "utf-8");
        //%E7%AF%AE%E7%90%83 -> 篮球 (不相信可以百度解码试一试)
        //如果是中文，那浏览器就保存成这样
        Cookie cookie3 = new Cookie("hobby",basketball);

        System.out.println(basketball);
        //然后在解码看一下
        String decode = URLDecoder.decode(basketball, "utf-8");
        System.out.println("basketball= "+decode);//篮球

        response.setContentType("text/html;charset=utf-8");
        //将cookie发送给浏览器，让浏览器将cookie保存
        response.addCookie(cookie);
        response.addCookie(cookie2);
        response.addCookie(cookie3);
        PrintWriter writer = response.getWriter();
        writer.println("<h1>创建cookie成功</h1>");
        writer.close();
    }
}
